//
//  NotDisturbViewController.m
//  SmartCup
//
//  Created by Kendama on 2017/5/18.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "NotDisturbViewController.h"

@interface NotDisturbViewController ()
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UILabel *buttonLabel;
@property (strong, nonatomic) UIButton *switchButton;
@property (strong, nonatomic) UIView *buttonView;


@end

@implementation NotDisturbViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)refreshBaseControlValue {
    [self setNavigationTitle:@"免打扰" titleColor:[UIColor whiteColor]];
    self.navigationBar.backgroundColor = [UIColor colorWithHexString:@"3E76F6"];
        self.view.backgroundColor = [UIColor colorWithHexString:@"#F1F3F9"];
    [self setLeftButtonImage:[UIImage imageNamed:@"nav_icon_back"]];
    
    [self layoutSubviews];
}

- (void) layoutSubviews{
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(64+px1920Height(40));
        make.left.equalTo(self.view).with.offset(px1080Width(51));
        make.right.equalTo(self.view).with.offset(px1080Width(51));
        make.height.mas_equalTo(px1920Height(36));
    }];
    
    [self.buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).with.offset(px1920Height(30));
        make.width.equalTo(self.view);
        make.height.mas_equalTo(px1920Height(168));
    }];
    
    [self.buttonLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.buttonView);
        make.left.equalTo(self.view).with.offset(px1080Width(51));
        make.width.mas_equalTo(px1080Width(200));
        make.height.equalTo(self.buttonView);
    }];
    
    [self.switchButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.equalTo(self.buttonView);
        make.right.equalTo(self.view).with.offset(-px1080Width(51));
        make.width.mas_equalTo(px1080Width(136));
        make.height.mas_equalTo(px1920Height(80));
        make.top.equalTo(self.buttonView).with.offset(px1920Height(50));
        make.bottom.equalTo(self.buttonView).with.offset(-px1920Height(50));

    }];
}

- (void)didClickSwitchButton {
    self.switchButton.selected = !self.switchButton.selected;
    if (self.switchButton.selected) {
        self.buttonLabel.text = @"开启";
        DTCSAVE_OBJECT(@"YES", @"notDisturb");
    } else {
        self.buttonLabel.text = @"关闭";
        DTCSAVE_OBJECT(@"NO", @"notDisturb");
    }
    [self sendNotification];
}

- (void) sendNotification{
    [[DTCLocalPushManager defalutService] removeAllLocalNotification];
    NSArray *data = [RemindModel selectAllObject];
    for (RemindModel *remind in data) {
        if (remind.switchMark) {
            NSInteger count = remind.count;
            NSInteger startSP = [self getYearMouthDayWithTime:remind.startTime];
            NSInteger endSP = [self getYearMouthDayWithTime:remind.endTime];
            NSInteger equal = [self calculateAverageWithCount:count andTimeSp:startSP andTimeSp2:endSP];
            NSInteger nowSP = [[NSDate date] timeIntervalSince1970];
            
            if (count == 0) { // 自动模式
                NSInteger month = [[self getMonth] intValue];
                if (3 <= month && month <= 5) { // 春季
                    count = [self calculateCountWithMinute:75 andStartTime:startSP andEndTime:endSP];
                    equal = 75*60;
                } else if (6 <= month && month <= 8) { // 夏季
                    count = [self calculateCountWithMinute:60 andStartTime:startSP andEndTime:endSP];
                    equal = 60*60;
                } else if (9 <= month && month <= 11) { // 秋季
                    count = [self calculateCountWithMinute:75 andStartTime:startSP andEndTime:endSP];
                    equal = 75*60;
                } else { // 冬季
                    count = [self calculateCountWithMinute:90 andStartTime:startSP andEndTime:endSP];
                    equal = 90*60;
                }
                
            }
            
            for (int j = 0; j < 30; j++) {
                for (int i = 1; i <= count; i++) {
                    NSString *sound = [NSString string];
                    if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
                        sound = @"sound.caf";
                    } else {
                        sound = @"silent.caf";
                    }
                    NSLog(@"自动模式：%li",startSP + equal*i + 60*60*24*j);
                    NSInteger notificationSp = startSP + equal*i + 60*60*24*j;
                    if (notificationSp > nowSP) {
                        NSDate *date = [NSDate dateWithTimeIntervalSince1970:notificationSp];
                        [[DTCLocalPushManager defalutService]addLocalNotificationByBody:[NSString stringWithFormat:@"一杯子提醒您该%@啦",remind.type] sound:sound date:date userInfo:@{@"remind":remind.type} repeat:NO];
                    }
                    
                }
                
            }
        }
    }
    
}

// 获取当前月份
- (NSString *)getMonth
{
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM"];
    NSString *monthString = [dateFormatter stringFromDate:date];
    monthString = [monthString substringToIndex:2];
    return monthString;
}

- (NSInteger)calculateCountWithMinute:(NSInteger)minute andStartTime:(NSInteger)startTime andEndTime:(NSInteger)endTime {
    NSInteger count;
    count = (endTime - startTime)/60/minute;
    
    if (count < 1) {
        return 1;
    }
    return count;
}

//- (void) sendNotification{
//    [[DTCLocalPushManager defalutService] removeAllLocalNotification];
//    NSArray *data = DTCEXRACT_OBJECT(@"remind");
//    for (NSDictionary *dict in data) {
//        if ([dict[@"switch"] isEqualToString:@"YES"]) {
////            NSLog(@"开始时间：%li",(long)[self getYearMouthDayWithTime:dict[@"startTime"]]);
//            NSInteger count = [dict[@"count"] intValue];
//            NSInteger startSP = [self getYearMouthDayWithTime:dict[@"startTime"]];
//            NSInteger endSP = [self getYearMouthDayWithTime:dict[@"endTime"]];
//            NSInteger equal = [self calculateAverageWithCount:count andTimeSp:startSP andTimeSp2:endSP];
//            for (int j = 0; j < 30; j++) {
//                for (int i = 1; i <= count; i++) {
//                    //                    NSLog(@"提示：%li",startSP + equal*i + 60*60*24*j);
//                    NSString *sound = [NSString string];
//                    if (DTCEXRACT_OBJECT(@"notDisturb") == nil || [DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"NO"]) {
//                        sound = @"sound.caf";
//                    } else {
//                        sound = @"silent.caf";
//                    }
//                    
//                    NSDate *date = [NSDate dateWithTimeIntervalSince1970:startSP + equal*i + 60*60*24*j];
//                    [[DTCLocalPushManager defalutService]addLocalNotificationByBody:@"一杯子提醒您该喝水啦" sound:sound date:date userInfo:@{@"remind":@"water"} repeat:NO];
//                }
//            }
//        }
//    }
//}

- (NSInteger)calculateAverageWithCount:(NSInteger)count andTimeSp:(NSInteger)timeSp andTimeSp2:(NSInteger)timeSp2{
    NSInteger different = timeSp2 - timeSp;
    NSInteger equal = different/(count+1);
    return equal;
}

// 将某个时间点转换成时间戳
- (NSInteger)getYearMouthDayWithTime:(NSString *)time {
    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *formatTime = [NSString stringWithFormat:@"%@ %@",[dateFormatter stringFromDate:date],time];
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm"]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date2 = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date2 timeIntervalSince1970]] integerValue];
    return timeSp;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 懒加载
- (UIView *)buttonView
{
    if(!_buttonView)
    {
        UIView *superView = self.view;
        _buttonView = [[UIView alloc]init];
        _buttonView.backgroundColor = [UIColor whiteColor];
        [superView addSubview:_buttonView];
    }
    return _buttonView;
}

- (UILabel *)titleLabel
{
    if(!_titleLabel)
    {
        UIView *superView = self.view;
        _titleLabel = [[UILabel alloc]init];
        [superView addSubview:_titleLabel];
        [_titleLabel setFont:[UIFont systemFontOfSize:px1080Width(42)]];
        [_titleLabel setTextColor:[UIColor colorWithHexString:@"#9295A0"]];
        _titleLabel.text = @"关闭所有铃声，震动提醒";
    }
    return _titleLabel;
}

- (UILabel *)buttonLabel
{
    if(!_buttonLabel)
    {
        UIView *superView = self.buttonView;
        _buttonLabel = [[UILabel alloc]init];
        [superView addSubview:_buttonLabel];
        [_buttonLabel setFont:[UIFont systemFontOfSize:15]];
        [_buttonLabel setTextColor:[UIColor colorWithHexString:@"#3E76F6"]];
        if ([DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"YES"]) {
            _buttonLabel.text = @"开启";
        } else {
            _buttonLabel.text = @"关闭";
        }
    }
    return _buttonLabel;
}

- (UIButton *)switchButton
{
    if(!_switchButton)
    {
        UIView *superView = self.view;
        _switchButton = [[UIButton alloc]init];
        [superView addSubview:_switchButton];
        [_switchButton setBackgroundImage:[UIImage imageNamed:@"button_off"] forState:UIControlStateNormal];
        [_switchButton setBackgroundImage:[UIImage imageNamed:@"button_on"] forState:UIControlStateSelected];
        [_switchButton addTarget:self action:@selector(didClickSwitchButton) forControlEvents:UIControlEventTouchUpInside];
        if ([DTCEXRACT_OBJECT(@"notDisturb") isEqualToString:@"YES"]) {
            _switchButton.selected = YES;
        } else {
            _switchButton.selected = NO;
        }
    }
    return _switchButton;
}



@end
